// Import
window.WebTorrent = require('webtorrent') //require('webtorrent')
window.require('moment')
window.Plyr = require('plyr')


// Define torrent trackers, here you can define you're private trackers if you want
// Look at the scope of the variable!
var P2PCDNTrackers = [
    'udp://tracker.openbittorrent.com:80'
    , 'udp://tracker.internetwarriors.net:1337'
    , 'wss://tracker.openwebtorrent.com'
    , 'wss://tracker.fastcast.nz'
    , 'udp://tracker.leechers-paradise.org:6969'
];
// Custom endpoint
// Look at the scope of the variable!
//var P2PCDNEndpoint = '<?php echo $p2pCdn->getEndpoint(); ?>';
//var torrentId = '<?php echo $p2pCdn->getEndpoint(), 'video.mp4';?>';
//var torrentId = 'http://127.0.0.1:8080/video.mp4.torrent'
//var torrentId = 'magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel&tr=udp%3A%2F%2Fexplodie.org%3A6969&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Ftracker.empire-js.us%3A1337&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=wss%3A%2F%2Ftracker.btorrent.xyz&tr=wss%3A%2F%2Ftracker.fastcast.nz&tr=wss%3A%2F%2Ftracker.openwebtorrent.com&ws=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2F&xs=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2Fsintel.torrent'


//var lang_favoriting = "Favoriting...";
//var lang_posting = "Posting...";
var video_width = "640";
var video_height = "360";
//var evideo_vkey = "aaccd288f98b7c8723b6";

//var vid = 4890;
var torrent_exists = 1;
var ipfsPath = false;
var iOS = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform);
var videoAutoplay = true;
var iphoneVideo = true;
var hdVideo = true;

//var iphoneVideoSource = 'https://animalporn.rocks/media/videos/iphone/4890.mp4';
//var hdVideoSource = 'https://animalporn.rocks/media/videos/hd/4890.mp4';
//var iphoneVideoSource = 'https://cdn.sloppy.pink/videos/iphone/4890.mp4';
//var hdVideoSource = 'https://cdn.sloppy.pink/videos/hd/4890.mp4';
var videoFilesJson = [{"height": "", "label": null, "format": null, "file": "4890_."}];
var videoPoster = '/videos/thumb.png';
var h264Base = '/';
var vasset = 'assets/';


function prettyBytes(num) {
    var exponent, unit, neg = num < 0, units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
    if (neg) num = -num
    if (num < 1) return (neg ? '-' : '') + num + ' B'
    exponent = Math.min(Math.floor(Math.log(num) / Math.log(1000)), units.length - 1)
    num = Number((num / Math.pow(1000, exponent)).toFixed(2))
    unit = units[exponent]
    return (neg ? '-' : '') + num + ' ' + unit
}

$(document).ready(function () {

    // Create a video element
    var video = document.createElement('video')


    video.id = "video";
    video.className = 'video-js vjs-16-9 vjs-big-play-centered vjs-sublime-skin';
    video.controls = true;
    //videojs.MediaSource
    video.poster = videoPoster;
    //video.style.width='100%';

    if (videoAutoplay) {
        //video.data_setup = {autoplay: true};
        video['data-setup'] = '{"autoplay": true}';
    } else {
        video['data-setup'] = '{}';
    }

    var video_container = document.getElementsByClassName("video-container")[0];

    var evdiv = $('.video-embedded');
    var ewidth = evdiv.width();
    eheight = Math.round(ewidth / 1.777);
    evdiv.css("height", eheight);

    $(window).resize(function () {
        var evwidth = $('.video-embedded').width();
        evheight = Math.round(evwidth / 1.777);
        $('.video-embedded').css("height", evheight);
    });

    //torrent_exists = false;

    //iOS = true

    if (WebTorrent.WEBRTC_SUPPORT && torrent_exists && !iOS) {
        console.log("WebRTC supported and torrent data exists, using webtorrent.")

        //var torrentId = 'https://video.zoo.cab/media/torrents/' + vid + '.torrent';
        //var torrentId = vasset+'/media/torrents/' + vid + '.torrent';

        var client = new WebTorrent();

        var torrentAddOpts = {
            maxWebConns: 1
        }

        client.add(torrentId, torrentAddOpts, function (torrent) {
            // Torrents can contain many files. Let's use the .mp4 file
            var file = torrent.files.find(function (file) {
                return file.name.endsWith('.mp4')
            })


            file.renderTo(video)
            //file.renderTo(video)
            //src=file.getBlobURL()
            var src = $("video").attr("src");
            //video.src=src
            //video.options.src=src


            setInterval(onProgress, 500)
            onProgress()

            // Statistics
            function onProgress() {
                var stats_string = '';
                var stats_el = document.getElementById("webtorrent_stats");

                // Peers
                //$numPeers.innerHTML = torrent.numPeers + (torrent.numPeers === 1 ? ' peer' : ' peers')
                stats_string += torrent.numPeers + (torrent.numPeers === 1 ? ' peer' : ' peers')

                // Progress
                var percent = Math.round(torrent.progress * 100 * 100) / 100
                //$progressBar.style.width = percent + '%'
                //$downloaded.innerHTML = prettyBytes(torrent.downloaded)
                //$total.innerHTML = prettyBytes(torrent.length)

                // Remaining time
                var remaining
                if (torrent.done) {
                    remaining = 'Done.'
                } else {
                    remaining = moment.duration(torrent.timeRemaining / 1000, 'seconds').humanize()
                    remaining = remaining[0].toUpperCase() + remaining.substring(1) + ' remaining.'
                }
                //$remaining.innerHTML = remaining

                // Speed rates
                //$downloadSpeed.innerHTML = prettyBytes(torrent.downloadSpeed) + '/s'
                stats_string += "  " + prettyBytes(torrent.downloadSpeed) + '/s' + '<i class="glyphicon glyphicon-arrow-down"></i>'
                //$uploadSpeed.innerHTML = prettyBytes(torrent.uploadSpeed) + '/s'
                stats_string += " : " + prettyBytes(torrent.uploadSpeed) + '/s' + '<i class="glyphicon glyphicon-arrow-up"></i>'

                stats_el.innerHTML = stats_string;
            }

        })

        video_container.appendChild(video);


        //var ve_script = document.createElement('script');
        //ve_script.src = vasset+"video-js-events.js";
        //document.getElementsByTagName('head')[0].appendChild(ve_script);
    } else {
        console.log("WebRTC NOT support, using local videojs.")
        $("#webtorrent_stats").hide();

        if (iphoneVideo) {
            var iphonesource = document.createElement('source');
            iphonesource.src = iphoneVideoSource;
            iphonesource.type = 'video/mp4';
            //iphonesource.label	= 'SD';
            //iphonesource.res		= 720;
            iphonesource.setAttribute('label', 'SD');
            iphonesource.setAttribute('res', 720);
            video.appendChild(iphonesource);

            //if( hdVideo ) {
            //var hdsource				= document.createElement('source');
            //hdsource.src				= hdVideoSource;

            //hdsource.src =

            //hdsource.type				= 'video/mp4';
            //hdsource.label			= 'HD';
            //hdsource.res				= 1080;
            //hdsource.setAttribute('label', 'HD');
            //hdsource.setAttribute('res', 1080);

            //if( ipfsPath ) {
            //	hdsource.src = weightedRandomHost() + '/ipfs/' + ipfsPath + '/' + vid + '.mp4';
            //	video.appendChild(hdsource);
            //}
            //}

            video_container.appendChild(video);
            //video.appendChild(source)
            //var ve_script = document.createElement('script');
            //ve_script.src = vasset+"video-js-events.js";
            //document.getElementsByTagName('head')[0].appendChild(ve_script);
        } else {
            //h264

            //if(hostRand > 5) {
            h264Base = 'https://cdn.sloppy.pink' + h264Base;
            //}

            videoFilesJson.forEach(function (vf) {
                if (!isNaN(vf.height)) {

                    if (vf.height == 480) return;
                    if (vf.height == 720) return;
                    if (vf.height == 1080) return;

                    console.log(vf);
                    var h264source = document.createElement('source');
                    h264source.src = h264Base + vf.file;
                    h264source.type = 'video/mp4';
                    //h264source.label      = vf.label;
                    //h264source.res        = vf.height;
                    h264source.setAttribute('label', vf.label);
                    h264source.setAttribute('res', vf.height);
                    console.log(h264source)
                    video.appendChild(h264source);
                }
                video_container.appendChild(video);
                //var ve_script = document.createElement('script');
                //ve_script.src = vasset+"video-js-events.js";
                //document.getElementsByTagName('head')[0].appendChild(ve_script);
            });
        }
    }

    //video_container.appendChild(video);
    //var player = videojs('video');
    const player = new Plyr(video);
    /* player.ready(function () {
         $('.video-container').mousedown(function (event) {
             if (event.which === 3) {
                 $('.video-container').bind('contextmenu', function () {
                     return false;
                 });
             } else {
                 $('.video-container').unbind('contextmenu');
             }
         });

     });*/
});